package com.atguigu.atomic;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/9
 */

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多线程下，对整型变量进行并发修改，比较普通整型和原子整型的结果
 */
public class CASDemo2 {
    public static void main(String[] args) throws InterruptedException {
        MyNumber myNumber = new MyNumber();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    myNumber.setNumber();
                    myNumber.setAtomicNumber();
                }

            }, "t" + i).start();
        }

        // 保证所有子线程完成修改
        TimeUnit.SECONDS.sleep(2);
        // 查看结果
        int number = myNumber.getNumber();
        int atomicNumber = myNumber.getAtomicNumber();
        System.out.println("number = " + number);
        System.out.println("atomicNumber = " + atomicNumber);

    }
}


class MyNumber {
    int number = 0;
    AtomicInteger atomicNumber = new AtomicInteger();

    public int getNumber() {
        return number;
    }

    public void setNumber() {
        this.number++;
    }

    public int getAtomicNumber() {
        return atomicNumber.get();
    }

    public void setAtomicNumber() {
        this.atomicNumber.getAndIncrement();
    }
}


